package com.tencent.sr.iris.basic.mp.dependency;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.region.Region;
import com.tencent.sr.rmall.springbootstarter.utils.JsonUtils;
import java.net.URL;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CosDependency {

    @Value("${iris.cos.appId:''}")
    private String appId;

    @Value("${iris.cos.secretId:''}")
    private String secretId;

    @Value("${iris.cos.secretKey:''}")
    private String secretKey;

    @Value("${iris.cos.bucket:''}")
    private String bucket;

    @Value("${iris.cos.region:''}")
    private String regionName;

    public String getBucket() {
        return this.bucket;
    }

    public String getRegion() {
        return this.regionName;
    }

    /**
     * getPreSignedUrl
     * @param objPath
     * @return
     */
    public URL getPreSignedUrl(String objPath) {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(regionName));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);

        //有效期10分钟
        GeneratePresignedUrlRequest req =
                new GeneratePresignedUrlRequest(bucket, objPath, HttpMethodName.POST);
        Date expirationDate = new Date(System.currentTimeMillis() + 10L * 60L * 1000L);
        req.setExpiration(expirationDate);

        //req.addRequestParameter("param1", "value1");
        //req.putCustomRequestHeader("header1", "value1");
        URL url = cosClient.generatePresignedUrl(req);
        cosClient.shutdown();
        log.info("new signed url: {} ", JsonUtils.toJsonString(url));
        return url;
    }

    /**
     * setPublicRead
     * @param objPath
     */
    public void setPublicRead(String objPath) {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(regionName));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);

        log.info("set {} to publicRead", objPath);
        cosClient.setObjectAcl(bucket, objPath, CannedAccessControlList.PublicRead);

        cosClient.shutdown();
    }

}
